package com.ingrun.tuboshu.utils;


import lombok.Getter;
import org.slf4j.MDC;

@Getter
public class Response<T> {

    private Integer code;

    private String message;

    private final String requestId = MDC.get("tl");

    private T data;

    /**
     * 构造方法私有化，不允许外部new Response
     *
     * @param data
     */
    private Response(T data) {
        this(data, ResponseEnum.SUCCESS.getMessage(), ResponseEnum.SUCCESS.getCode());
    }

    /**
     * 创建 返回成功 失败的 结果
     *
     * @param data
     * @param message
     * @param code
     */
    private Response(T data, String message, Integer code) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    /**
     * 构造方法私有化，不允许外部new Response
     *
     * @param responseEnum
     */
    private Response(ResponseEnum responseEnum) {
        if (null == responseEnum) {
            return;
        }
        this.code = responseEnum.getCode();
        this.message = responseEnum.getMessage();
    }

    /**
     * 成功时调用
     *
     * @param
     * @param <T>
     * @return
     */
    public static <T> Response<T> success() {
        return success(null);
    }

    /**
     * 成功时调用
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Response<T> success(T data) {
        return new Response<T>(data);
    }

    /**
     * 失败时调用
     *
     * @param
     * @param <T>
     * @return
     */
    public static <T> Response error() {
        return error(ResponseEnum.ERROR);
    }

    /**
     * 失败时调用
     *
     * @param responseEnum
     * @param <T>
     * @return
     */
    public static <T> Response<T> error(ResponseEnum responseEnum) {
        return new Response<T>(responseEnum);
    }

    /**
     * 返回失败 的提示语
     *
     * @param data
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> Response<T> error(T data, String msg) {
        return new Response<T>(data, msg, ResponseEnum.ERROR.getCode());
    }

    public static <T> Response<String> error(ResponseException exception) {
        return new Response<>(exception.getErrorId(), exception.getResponseEnum().getMessage(), exception.getResponseEnum().getCode());
    }

    public static <T> Response<T> errorParams(T data, String msg) {
        return new Response<T>(data, msg == "" ? ResponseEnum.BAD_REQUEST.getMessage() : msg, ResponseEnum.BAD_REQUEST.getCode());
    }

    /**
     * 返回成功 的提示语
     *
     * @param data
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> Response<T> success(T data, String msg) {

        return new Response<T>(data, msg, ResponseEnum.SUCCESS.getCode());
    }

    public Response<T> setCode(Integer code) {
        this.code = code;
        return this;
    }

    public Response<T> setMessage(String message) {
        this.message = message;
        return this;
    }

    public Response<T> setData(T data) {
        this.data = data;
        return this;
    }

}
